package iotwisp.school.api.interceptor;

import com.alibaba.fastjson.JSON;

import iotwisp.base.cqrs.BusinessException;
import iotwisp.base.rest.JSONResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@Slf4j
@ControllerAdvice
public class ExceptionRestHandler extends ResponseEntityExceptionHandler {

	/**
	 * 异常
	 * 
	 * @param ex
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ExceptionHandler({ BusinessException.class })
	public ResponseEntity<Object> handleExceptionInternal(Exception ex, @Nullable Object body, WebRequest request) {
		if (ex != null) {
			ex.printStackTrace();
			BusinessException e = (BusinessException) ex;
			try {
				JSONResultDTO jsonResultDTO = JSON.parseObject(e.getMessage(), JSONResultDTO.class);
				return ResponseEntity.ok(createFailResult(jsonResultDTO.getCode(), jsonResultDTO.getMsg()));
			} catch (Exception e2) {
			}
			return ResponseEntity.ok(createFailResult(e.getCode(), "未知错误"));

		}

		return ResponseEntity.ok(body);
	}

	private JSONResultDTO createFailResult(String code, String msg) {
		JSONResultDTO result = new JSONResultDTO();
		result.setCode(code);
		result.setMsg(msg);
		result.setData(null);
		return result;
	}
}